//
//  hvArrowContainerView.m
//  CustomMapCalloutAnnotation
//
//  Created by moon on 14-5-8.
//  Copyright (c) 2014年 hv. All rights reserved.
//

#import "hvArrowContainerView.h"

@implementation hvArrowContainerView

- (void)setupProperties{
	_cornerRadius = 8;
	_arrowSize = CGSizeMake(10, 10);
	_arrowMargin = 0;
	_arrowOffset = 0;
	CGFloat m = 10;
	_contentMargin = UIEdgeInsetsMake(m, m, m, m);
	_borderWidth = 1;
	_borderColor = [UIColor blackColor];
	_supportedArrowDirections = UIPopoverArrowDirectionAny;
	
	[self setBackgroundColor:[UIColor clearColor]];
	_tintColor = _tintColor2 = [UIColor whiteColor];
	
	self.layer.shadowOpacity = [[[UIDevice currentDevice] systemVersion] floatValue]>=7.0?0.1:0.5;	//ios7風格適配
	self.layer.shadowOffset = CGSizeMake(2, 2);
	self.layer.shadowRadius = 2;
	self.clipsToBounds = NO;
	self.userInteractionEnabled = YES;
}
- (id)init{
	if(self=[super init]){
		[self setupProperties];
	}
	return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder{
	if(self=[super initWithCoder:aDecoder]){
		[self setupProperties];
	}
	return self;
}
- (id)initWithFrame:(CGRect)frame{
	if(self=[super initWithFrame:frame]){
		[self setupProperties];
	}
	return self;
}

- (void)setBorderColor:(UIColor *)borderColor{
	if(![_borderColor isEqual:borderColor]){
		_borderColor = borderColor;
		[self setNeedsDisplay];
	}
}
- (void)setBorderWidth:(CGFloat)borderWidth{
	if(_borderWidth!=borderWidth){
		_borderWidth = borderWidth;
		[self setNeedsDisplay];
	}
}
- (void)setTintColor:(UIColor *)tintColor{
	if(![_tintColor isEqual:tintColor]){
		_tintColor = tintColor;
		[self setNeedsDisplay];
	}
}
- (void)setTintColor2:(UIColor *)tintColor2{
	if (![_tintColor2 isEqual:tintColor2]) {
		_tintColor2 = tintColor2;
		[self setNeedsDisplay];
	}
}
- (void)setCornerRadius:(CGFloat)cornerRadius{
	if(_cornerRadius!=cornerRadius){
		_cornerRadius = cornerRadius;
		[self setNeedsDisplay];
	}
}
- (void)setBackgroundColor:(UIColor *)backgroundColor{
	self.tintColor = self.tintColor2 = backgroundColor;
	[super setBackgroundColor:[UIColor clearColor]];
}
- (UIColor *)backgroundColor{
	if([self.tintColor isEqual:self.tintColor2]){
		return self.tintColor;
	}else{
		return [super backgroundColor];
	}
}

- (id)initWithContentView:(UIView *)contentView anchorRect:(CGRect)anchorRect displayArea:(CGRect)displayArea supportedArrowDirections:(UIPopoverArrowDirection)supportedArrowDirections{
	if(self=[self initWithFrame:CGRectZero]){
		_anchorRect = anchorRect;
		_displayArea = displayArea;
		_supportedArrowDirections = supportedArrowDirections;
		self.contentView = contentView;
		[self refresh];
	}
	return self;
}
- (void)refresh{
	[self calGeometry];
	[self setNeedsDisplay];
}
/**
 *	計算各種尺寸
 */
- (void)calGeometry{
	//計算出彈出框圓角矩形區域的尺寸,大小為contentSize加上self.contentMargin
	CGSize contentSize = self.contentView.bounds.size;
	CGSize correctedSize = CGSizeMake(contentSize.width+self.contentMargin.left+self.contentMargin.right, contentSize.height+self.contentMargin.top+self.contentMargin.bottom);
	[self determineGeometryForRoundedRectangleSize:correctedSize anchorRect:self.anchorRect displayArea:self.displayArea supportedArrowDirections:self.supportedArrowDirections];
}

/**
 *	計算出圓角矩形區域的frame,箭頭的方向,箭頭的frame,self.frame
 *	@param roundedRectSize:圓角矩形的尺寸,大小為contentSize加上self.contentMargin
 */
- (void)determineGeometryForRoundedRectangleSize:(CGSize)roundedRectangleSize anchorRect:(CGRect)anchorRect displayArea:(CGRect)displayArea supportedArrowDirections:(UIPopoverArrowDirection)supportedArrowDirections {
	UIPopoverArrowDirection theArrowDirection = UIPopoverArrowDirectionUp;
	
	_roundedRectangleRect = CGRectNull;					//圓角矩形邊框的frame
	_arrowRect = CGRectZero;							//箭頭圖/箭頭形狀的frame
	_arrowDirection = UIPopoverArrowDirectionUnknown;	//計算出來的箭頭方向
	
	CGFloat biggestSurface = 0.0f;
	
	CGSize arrowSize = self.arrowSize;
	
	CGRect finalArrowFrame = CGRectZero;			//箭頭在displayArea座標系中的frame
	CGRect finalRoundedRectangleFrame = CGRectZero;	//圓角矩形背景在displayArea座標系中的frame
	CGRect finalFrame = CGRectZero;					//self.frame值
	CGFloat distanceFactorOfCenterPoint = CGFLOAT_MAX;	//值=arrowRect的中點與_roundedRectangleRect的中心點之間的距離/_roundedRectangleRect的邊長,用於當兩個方向計算出來的_roundedRectangleRect面積一樣時,取該值更小者為更優方向
	NSUInteger directions[4] = {UIPopoverArrowDirectionDown,UIPopoverArrowDirectionUp,UIPopoverArrowDirectionLeft,UIPopoverArrowDirectionRight};	//計算順序為v,^,<,>
	for (int i=0; i<4; i++) {
		theArrowDirection = directions[i];
		if ((supportedArrowDirections & theArrowDirection)) {	//判斷是否在指定的可選方向中
			
			CGRect arrowFrame = CGRectZero;	//箭頭在displayArea座標系中的frame
			CGRect roundBgFrame = CGRectZero;	//圓角矩形背景在displayArea座標系中的frame
			CGPoint anchorPoint = CGPointZero;	//箭頭中間點的座標值
			CGFloat fator = CGFLOAT_MAX;	//參照distanceFactorOfCenterPoint的說明
			switch (theArrowDirection) {
				case UIPopoverArrowDirectionUp:	//^
					/*
					  ______
					 |______|
					  __/\____
					 |  pop   |
					 |content |
					 |        |
					 |________|
					 */
					anchorPoint = CGPointMake(CGRectGetMidX(anchorRect), CGRectGetMaxY(anchorRect));
					
                    // Check if anchorPoint is under the displayArea (due to keyboard showing)
                    if (anchorPoint.y > CGRectGetMaxY(displayArea)) {
                        // Skip this test since we need ArrowDirectionDown in this case.
                        NSAssert(supportedArrowDirections & UIPopoverArrowDirectionDown, @"ArrowDirectionDown is needed but wasn't allowed");
                        break;
                    }
					arrowSize = self.arrowSize;
					
					arrowFrame = CGRectMake(anchorPoint.x-arrowSize.width*0.5, anchorPoint.y, arrowSize.width, arrowSize.height);
					arrowFrame.origin.y += self.arrowMargin;	//加上偏移量
					roundBgFrame = CGRectMake(anchorPoint.x-(roundedRectangleSize.width*0.5), CGRectGetMaxY(arrowFrame), roundedRectangleSize.width, roundedRectangleSize.height);
					roundBgFrame.origin.y -= self.arrowOffset;	//該偏移量使得箭頭與背景能夠重疊或分離
					
					//如果寬度超過顯示寬度,縮小
					if(CGRectGetWidth(roundBgFrame)>CGRectGetWidth(displayArea)){
						roundBgFrame.size.width -= CGRectGetWidth(roundBgFrame)-CGRectGetWidth(displayArea);
					}
					//如果背景超過右邊框,背景左移
					if(CGRectGetMaxX(roundBgFrame)>CGRectGetMaxX(displayArea)){
						roundBgFrame.origin.x -= CGRectGetMaxX(roundBgFrame)-CGRectGetMaxX(displayArea);
					}
					//如果背景超過左邊框,背景右移
					if(CGRectGetMinX(roundBgFrame)<CGRectGetMinX(displayArea)){
						roundBgFrame.origin.x += CGRectGetMinX(displayArea)-CGRectGetMinX(roundBgFrame);
					}
					//如果背景底部超過邊框,背景減小高度
					if(CGRectGetMaxY(roundBgFrame)>CGRectGetMaxY(displayArea)){
						roundBgFrame.size.height -= CGRectGetMaxY(roundBgFrame)-CGRectGetMaxY(displayArea);
						if(roundBgFrame.size.height<0){
							roundBgFrame.size.height = 0;
						}
					}
					fator = ABS(anchorPoint.x-CGRectGetMidX(roundBgFrame))/CGRectGetWidth(roundBgFrame);
					
					break;
				case UIPopoverArrowDirectionDown:	//v
					/*
					  ________
					 |  pop   |
					 |content |
					 |        |
					 |__ _____|
					  __V__
					 |_____|
					 
					 */
					anchorPoint = CGPointMake(CGRectGetMidX(anchorRect), CGRectGetMinY(anchorRect));
					
                    // Check if anchorPoint is under the displayArea (due to keyboard showing)
                    if (anchorPoint.y > CGRectGetMaxY(displayArea)) {
                        // Shift the point to the visible area
                        anchorPoint.y = CGRectGetMaxY(displayArea);
						break;
                    }
					arrowSize = self.arrowSize;
					
                    arrowFrame = CGRectMake(anchorPoint.x-arrowSize.width*0.5, anchorPoint.y-arrowSize.height, arrowSize.width, arrowSize.height);
					arrowFrame.origin.y -= self.arrowMargin;	//加上偏移量
					roundBgFrame = CGRectMake(anchorPoint.x-(roundedRectangleSize.width*0.5), CGRectGetMinY(arrowFrame)-roundedRectangleSize.height, roundedRectangleSize.width, roundedRectangleSize.height);
					roundBgFrame.origin.y += self.arrowOffset;	//該偏移量使得箭頭與背景能夠重疊或分離
					
					//如果寬度超過顯示寬度,縮小
					if(CGRectGetWidth(roundBgFrame)>CGRectGetWidth(displayArea)){
						roundBgFrame.size.width -= CGRectGetWidth(roundBgFrame)-CGRectGetWidth(displayArea);
					}
					//如果背景超過右邊框,背景左移
					if(CGRectGetMaxX(roundBgFrame)>CGRectGetMaxX(displayArea)){
						roundBgFrame.origin.x -= CGRectGetMaxX(roundBgFrame)-CGRectGetMaxX(displayArea);
					}
					//如果背景超過左邊框,背景右移
					if(CGRectGetMinX(roundBgFrame)<CGRectGetMinX(displayArea)){
						roundBgFrame.origin.x += CGRectGetMinX(displayArea)-CGRectGetMinX(roundBgFrame);
					}
					//如果背景頂部超過邊框,背景減小高度
					if(CGRectGetMinY(roundBgFrame)<CGRectGetMinY(displayArea)){
						CGFloat diff = CGRectGetMinY(displayArea)-CGRectGetMinY(roundBgFrame);
						roundBgFrame.origin.y += diff;
						roundBgFrame.size.height -= diff;;
						if(roundBgFrame.size.height<0){
							roundBgFrame.origin.y += roundBgFrame.size.height;
							roundBgFrame.size.height = 0;
						}
					}
					fator = ABS(anchorPoint.x-CGRectGetMidX(roundBgFrame))/CGRectGetWidth(roundBgFrame);
					break;
				case UIPopoverArrowDirectionLeft://<
					/*
					        ________
					  ___  |  pop   |
					 |___|< content |
					       |        |
						   |________|
					 */
					anchorPoint = CGPointMake(CGRectGetMaxX(anchorRect), CGRectGetMidY(anchorRect));
					
                    // Check if anchorPoint is under the displayArea (due to keyboard showing)
                    if (anchorPoint.y > CGRectGetMaxY(displayArea)) {
                        // Skip this test since we need ArrowDirectionDown in this case.
                        NSAssert(supportedArrowDirections & UIPopoverArrowDirectionDown, @"ArrowDirectionDown is needed but wasn't allowed");
                        break;
                    }
					arrowSize = self.arrowSize;
					
                    arrowFrame = CGRectMake(anchorPoint.x, anchorPoint.y-arrowSize.height*0.5, arrowSize.width, arrowSize.height);
					arrowFrame.origin.x += self.arrowMargin;	//加上偏移量
					roundBgFrame = CGRectMake(CGRectGetMaxX(arrowFrame),anchorPoint.y-roundedRectangleSize.height*0.5,roundedRectangleSize.width,roundedRectangleSize.height);
					roundBgFrame.origin.x -= self.arrowOffset;	//該偏移量使得箭頭與背景能夠重疊或分離
					
					//如果高度超過顯示高度,縮小
					if(CGRectGetHeight(roundBgFrame)>CGRectGetHeight(displayArea)){
						roundBgFrame.size.width -= CGRectGetHeight(roundBgFrame)-CGRectGetHeight(displayArea);
					}
					//如果背景超過上邊框,背景下移
					if(CGRectGetMinY(roundBgFrame)<CGRectGetMinY(displayArea)){
						roundBgFrame.origin.y += CGRectGetMinY(displayArea)-CGRectGetMinY(roundBgFrame);
					}
					//如果背景超過下邊框,背景上移
					if(CGRectGetMaxY(roundBgFrame)>CGRectGetMaxY(displayArea)){
						roundBgFrame.origin.y -= CGRectGetMaxY(roundBgFrame)-CGRectGetMaxY(displayArea);
					}
					//如果背景右部超過邊框,背景減小寬度
					if(CGRectGetMaxX(roundBgFrame)>CGRectGetMaxX(displayArea)){
						roundBgFrame.size.width -= CGRectGetMaxX(roundBgFrame)-CGRectGetMaxX(displayArea);
						if(roundBgFrame.size.width<0){
							roundBgFrame.size.width = 0;
						}
					}
					fator = ABS(anchorPoint.y-CGRectGetMidY(roundBgFrame))/CGRectGetHeight(roundBgFrame);
					break;
				case UIPopoverArrowDirectionRight://>
					/*
					  ________
					 |   pop  |  ____
					 | content >|____|
					 |        |
					 |________|
					 */
					
					anchorPoint = CGPointMake(CGRectGetMinX(anchorRect), CGRectGetMidY(anchorRect));
                    
                    // Check if anchorPoint is under the displayArea (due to keyboard showing)
                    if (anchorPoint.y > CGRectGetMaxY(displayArea)) {
                        // Skip this test since we need ArrowDirectionDown in this case.
                        NSAssert((supportedArrowDirections & UIPopoverArrowDirectionDown), @"ArrowDirectionDown is needed but wasn't allowed");
                        break;
                    }
                    
					arrowSize = self.arrowSize;
					
                    arrowFrame = CGRectMake(anchorPoint.x-arrowSize.width, anchorPoint.y-arrowSize.height*0.5, arrowSize.width, arrowSize.height);
					arrowFrame.origin.x -= self.arrowMargin;	//加上偏移量
					roundBgFrame = CGRectMake(CGRectGetMinX(arrowFrame)-roundedRectangleSize.width,anchorPoint.y-roundedRectangleSize.height*0.5,roundedRectangleSize.width,roundedRectangleSize.height);
					roundBgFrame.origin.x += self.arrowOffset;	//該偏移量使得箭頭與背景能夠重疊或分離
					
					//如果高度超過顯示高度,縮小
					if(CGRectGetHeight(roundBgFrame)>CGRectGetHeight(displayArea)){
						roundBgFrame.size.width -= CGRectGetHeight(roundBgFrame)-CGRectGetHeight(displayArea);
					}
					//如果背景超過上邊框,背景下移
					if(CGRectGetMinY(roundBgFrame)<CGRectGetMinY(displayArea)){
						roundBgFrame.origin.y += CGRectGetMinY(displayArea)-CGRectGetMinY(roundBgFrame);
					}
					//如果背景超過下邊框,背景上移
					if(CGRectGetMaxY(roundBgFrame)>CGRectGetMaxY(displayArea)){
						roundBgFrame.origin.y -= CGRectGetMaxY(roundBgFrame)-CGRectGetMaxY(displayArea);
					}
					//如果背景左部超過邊框,背景減小寬度
					if(CGRectGetMinX(roundBgFrame)<CGRectGetMinX(displayArea)){
						CGFloat diff = CGRectGetMinX(displayArea)-CGRectGetMinX(roundBgFrame);
						roundBgFrame.origin.x += diff;
						roundBgFrame.size.width -= diff;
						if(roundBgFrame.size.width<0){
							roundBgFrame.origin.x += roundBgFrame.size.width;
							roundBgFrame.size.width = 0;
						}
					}
					fator = ABS(anchorPoint.y-CGRectGetMidY(roundBgFrame))/CGRectGetHeight(roundBgFrame);
					break;
				default:
					break;
			}
			//計算面積,只保留最大面積者,面積相同時,取fator最小者,彈出框更正方形者
			CGFloat surface = fabsf(roundBgFrame.size.width) * fabsf(roundBgFrame.size.height);
			BOOL change = NO;
			if (surface > biggestSurface) {
				change = YES;
			}else if(surface == biggestSurface){
				if(distanceFactorOfCenterPoint>fator){
					change = YES;
				}
			}
			if(change){
				distanceFactorOfCenterPoint = fator;
				biggestSurface = surface;
				finalArrowFrame = arrowFrame;
				finalRoundedRectangleFrame = roundBgFrame;
				finalFrame = CGRectUnion(arrowFrame, roundBgFrame);;
				_arrowDirection = theArrowDirection;
			}
		}
	}
	
	self.frame = finalFrame;
	CGPoint offset = self.frame.origin;
	_arrowRect = CGRectOffset(finalArrowFrame, -offset.x, -offset.y);
	_roundedRectangleRect = CGRectOffset(finalRoundedRectangleFrame, -offset.x, -offset.y);
	self.contentView.frame = self.contentRect;
	NSAssert(!CGRectEqualToRect(_roundedRectangleRect, CGRectNull), @"bgRect is null");
}

- (void)drawRect:(CGRect)rect{
	[self calGeometry];
	[self drawArrowAndRoundedRectangle:_roundedRectangleRect inContext:UIGraphicsGetCurrentContext()];
}
- (UIBezierPath *)arrowBorderPath{
	CGRect frame = _roundedRectangleRect;
	CGFloat cornerRadius = self.cornerRadius;
	UIPopoverArrowDirection arrowDirection = _arrowDirection;
	CGRect arrowRect = _arrowRect;
	
	// render arrow
	UIBezierPath *borderPath = [UIBezierPath bezierPath];
	
	CGRect bodyFrame = frame;
	CGPoint arrowStartPoint,arrowCenterPoint,arrowEndPoint;	//剪頭起始,中間,結束點
	CGPoint centerOfRightTop = CGPointMake(CGRectGetMaxX(bodyFrame)-cornerRadius, CGRectGetMinY(bodyFrame)+cornerRadius);	//右上角圓心
	CGPoint centerOfRightBottom = CGPointMake(CGRectGetMaxX(bodyFrame)-cornerRadius, CGRectGetMaxY(bodyFrame)-cornerRadius);//右下角圓心
	CGPoint centerOfLeftBottom = CGPointMake(CGRectGetMinX(bodyFrame)+cornerRadius, CGRectGetMaxY(bodyFrame)-cornerRadius);	//左下角圓心
	CGPoint centerOfLeftTop = CGPointMake(CGRectGetMinX(bodyFrame)+cornerRadius, CGRectGetMinY(bodyFrame)+cornerRadius);	//左上角圓心
	CGPoint gradientStartPoint,gradientEndPoint;	//漸變的起始與終止點
	
	//繪製邊框時,是按順時針方向繪製的,因此arrowStartPoint與arrowEndPoint也是按順時針方向計算的
	if(arrowDirection == UIPopoverArrowDirectionUp){	//^
		/*
		  ______
		 |______|
		  __/\____
		 |  pop   |
		 |content |
		 |        |
		 |________|
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMidX(arrowRect), CGRectGetMinY(arrowRect));
		
		gradientStartPoint = arrowCenterPoint;
		gradientEndPoint = CGPointMake(gradientStartPoint.x, CGRectGetMaxY(bodyFrame));
		
		CGFloat sp = (arrowRect.size.width*0.5/arrowRect.size.height)*(CGRectGetMinY(bodyFrame) - arrowCenterPoint.y);
		arrowStartPoint = CGPointMake(arrowCenterPoint.x-sp, CGRectGetMinY(bodyFrame));
		arrowEndPoint = CGPointMake(arrowCenterPoint.x+sp, CGRectGetMinY(bodyFrame));
		//進行邊境判斷
		if(arrowStartPoint.x<centerOfLeftTop.x){
			arrowStartPoint.x = centerOfLeftTop.x;
			arrowEndPoint.x = arrowStartPoint.x+2*sp;
		}
		if(arrowEndPoint.x>centerOfRightTop.x){
			arrowEndPoint.x = centerOfRightTop.x;
			arrowStartPoint.x = arrowEndPoint.x-2*sp;
		}
	}else if(arrowDirection == UIPopoverArrowDirectionDown){	//v
		/*
		 ________
		 |  pop   |
		 |content |
		 |        |
		 |__ _____|
		 __V__
		 |_____|
		 
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMidX(arrowRect), CGRectGetMaxY(arrowRect));
		
		gradientStartPoint = CGPointMake(arrowCenterPoint.x, CGRectGetMinY(bodyFrame));
		gradientEndPoint = arrowCenterPoint;
		
		CGFloat sp = (arrowRect.size.width*0.5/arrowRect.size.height)*(arrowCenterPoint.y-CGRectGetMaxY(bodyFrame));
		arrowStartPoint = CGPointMake(arrowCenterPoint.x+sp, CGRectGetMaxY(bodyFrame));
		arrowEndPoint = CGPointMake(arrowCenterPoint.x-sp, CGRectGetMaxY(bodyFrame));
		if(arrowStartPoint.x>centerOfRightBottom.x){
			arrowStartPoint.x = centerOfRightBottom.x;
			arrowEndPoint.x = arrowStartPoint.x-2*sp;
		}
		if(arrowEndPoint.x<centerOfLeftBottom.x){
			arrowEndPoint.x = centerOfLeftBottom.x;
			arrowStartPoint.x = arrowEndPoint.x+2*sp;
		}
		
	}else if(arrowDirection == UIPopoverArrowDirectionLeft){	//<
		/*
		        ________
		  ___  |  pop   |
		 |___|< content |
			   |        |
		       |________|
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMinX(arrowRect), CGRectGetMidY(arrowRect));
		
		gradientStartPoint = CGPointMake(CGRectGetMidX(bodyFrame), CGRectGetMinY(bodyFrame));
		gradientEndPoint = CGPointMake(gradientStartPoint.x, CGRectGetMaxY(bodyFrame));
		
		CGFloat sp = (arrowRect.size.height*0.5/arrowRect.size.width)*(CGRectGetMinX(bodyFrame)-arrowCenterPoint.x);
		arrowStartPoint = CGPointMake(CGRectGetMinX(bodyFrame), arrowCenterPoint.y+sp);
		arrowEndPoint = CGPointMake(CGRectGetMinX(bodyFrame), arrowCenterPoint.y-sp);
		if(arrowStartPoint.y>centerOfLeftBottom.y){
			arrowStartPoint.y = centerOfLeftBottom.y;
			arrowEndPoint.y = arrowStartPoint.y-2*sp;
		}
		if(arrowEndPoint.y<centerOfLeftTop.y){
			arrowEndPoint.y = centerOfLeftTop.y;
			arrowStartPoint.y = arrowEndPoint.y+2*sp;
		}
	}else if(arrowDirection == UIPopoverArrowDirectionRight){	//>
		/*
		  ________
		 |   pop  |  ____
		 | content >|____|
		 |        |
		 |________|
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMaxX(arrowRect), CGRectGetMinY(arrowRect));
		
		gradientStartPoint = CGPointMake(CGRectGetMidX(bodyFrame), CGRectGetMinY(bodyFrame));
		gradientEndPoint = CGPointMake(gradientStartPoint.x, CGRectGetMaxY(bodyFrame));
		
		CGFloat sp = (arrowRect.size.height*0.5/arrowRect.size.width)*(arrowCenterPoint.x-CGRectGetMaxX(bodyFrame));
		arrowStartPoint = CGPointMake(CGRectGetMaxX(bodyFrame), arrowCenterPoint.y-sp);
		arrowEndPoint = CGPointMake(CGRectGetMaxX(bodyFrame), arrowCenterPoint.y+sp);
		if(arrowStartPoint.y<centerOfRightTop.y){
			arrowStartPoint.y = centerOfRightTop.y;
			arrowEndPoint.y = arrowStartPoint.y+2*sp;
		}
		if(arrowEndPoint.y>centerOfRightBottom.y){
			arrowEndPoint.y = centerOfRightBottom.y;
			arrowStartPoint.y = arrowEndPoint.y-2*sp;
		}
	}else{
	}
	
	//繪製外框路徑
	CGFloat angle = 0;
	
	[borderPath moveToPoint:CGPointMake(CGRectGetMaxX(bodyFrame), centerOfRightTop.y)];
	if(arrowDirection==UIPopoverArrowDirectionRight){	//>
		[borderPath addLineToPoint:arrowStartPoint];
		[borderPath addLineToPoint:arrowCenterPoint];
		[borderPath addLineToPoint:arrowEndPoint];
	}
	[borderPath addLineToPoint:CGPointMake(CGRectGetMaxX(bodyFrame), centerOfRightBottom.y)];
	[borderPath addArcWithCenter:centerOfRightBottom radius:cornerRadius startAngle:angle endAngle:(angle+M_PI_2) clockwise:YES];
	angle+=M_PI_2;
	if(arrowDirection==UIPopoverArrowDirectionDown){	//v
		[borderPath addLineToPoint:arrowStartPoint];
		[borderPath addLineToPoint:arrowCenterPoint];
		[borderPath addLineToPoint:arrowEndPoint];
	}
	[borderPath addLineToPoint:CGPointMake(centerOfLeftBottom.x, CGRectGetMaxY(bodyFrame))];
	[borderPath addArcWithCenter:centerOfLeftBottom radius:cornerRadius startAngle:angle endAngle:(angle+M_PI_2) clockwise:YES];
	angle+=M_PI_2;
	if(arrowDirection==UIPopoverArrowDirectionLeft){	//<
		[borderPath addLineToPoint:arrowStartPoint];
		[borderPath addLineToPoint:arrowCenterPoint];
		[borderPath addLineToPoint:arrowEndPoint];
	}
	[borderPath addLineToPoint:CGPointMake(CGRectGetMinX(bodyFrame), centerOfLeftTop.y)];
	[borderPath addArcWithCenter:centerOfLeftTop radius:cornerRadius startAngle:angle endAngle:(angle+M_PI_2) clockwise:YES];
	angle+=M_PI_2;
	if(arrowDirection==UIPopoverArrowDirectionUp){	//^
		[borderPath addLineToPoint:arrowStartPoint];
		[borderPath addLineToPoint:arrowCenterPoint];
		[borderPath addLineToPoint:arrowEndPoint];
	}
	[borderPath addLineToPoint:CGPointMake(centerOfRightTop.x, CGRectGetMinY(bodyFrame))];
	[borderPath addArcWithCenter:centerOfRightTop radius:cornerRadius startAngle:angle endAngle:(angle+M_PI_2) clockwise:YES];
	angle+=M_PI_2;
	[borderPath closePath];
	
	[self.borderColor set];
	borderPath.lineWidth = self.borderWidth;
	borderPath.lineJoinStyle = kCGLineJoinRound;
	borderPath.lineCapStyle = kCGLineCapRound;
	return borderPath;
}
/**
 *	繪製箭頭與圓角矩形邊框
 */
- (void)drawArrowAndRoundedRectangle:(CGRect)frame inContext:(CGContextRef)context{
	UIPopoverArrowDirection arrowDirection = _arrowDirection;
	CGRect arrowRect = _arrowRect;
	
	// render arrow
	UIBezierPath *borderPath = [self arrowBorderPath];
	
	// render body
	[borderPath addClip];
	
	CGRect bodyFrame = frame;
	CGPoint arrowCenterPoint;	//剪頭起始,中間,結束點
	CGPoint gradientStartPoint,gradientEndPoint;	//漸變的起始與終止點
	
	//繪製邊框時,是按順時針方向繪製的,因此arrowStartPoint與arrowEndPoint也是按順時針方向計算的
	if(arrowDirection == UIPopoverArrowDirectionUp){	//^
		/*
		  ______
		 |______|
		  __/\____
		 |  pop   |
		 |content |
		 |        |
		 |________|
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMidX(arrowRect), CGRectGetMinY(arrowRect));
		
		gradientStartPoint = arrowCenterPoint;
		gradientEndPoint = CGPointMake(gradientStartPoint.x, CGRectGetMaxY(bodyFrame));
	}else if(arrowDirection == UIPopoverArrowDirectionDown){	//v
		/*
		  ________
		 |  pop   |
		 |content |
		 |        |
		 |__ _____|
		  __V__
		 |_____|
		 
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMidX(arrowRect), CGRectGetMaxY(arrowRect));
		
		gradientStartPoint = CGPointMake(arrowCenterPoint.x, CGRectGetMinY(bodyFrame));
		gradientEndPoint = arrowCenterPoint;
	}else if(arrowDirection == UIPopoverArrowDirectionLeft){	//<
		/*
		        ________
		  ___  |  pop   |
		 |___|< content |
		       |        |
		       |________|
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMinX(arrowRect), CGRectGetMidY(arrowRect));
		
		gradientStartPoint = CGPointMake(CGRectGetMidX(bodyFrame), CGRectGetMinY(bodyFrame));
		gradientEndPoint = CGPointMake(gradientStartPoint.x, CGRectGetMaxY(bodyFrame));
	}else if(arrowDirection == UIPopoverArrowDirectionRight){	//>
		/*
		  ________
		 |   pop  |  ____
		 | content >|____|
		 |        |
		 |________|
		 */
		arrowCenterPoint = CGPointMake(CGRectGetMaxX(arrowRect), CGRectGetMinY(arrowRect));
		
		gradientStartPoint = CGPointMake(CGRectGetMidX(bodyFrame), CGRectGetMinY(bodyFrame));
		gradientEndPoint = CGPointMake(gradientStartPoint.x, CGRectGetMaxY(bodyFrame));
	}else{
	}
	
	//繪製漸變
	[self drawGradientWithContext:context gradientStartPoint:gradientStartPoint gradientEndPoint:gradientEndPoint];
	
	//繪製邊框
	[borderPath stroke];
}

- (void)drawGradientWithContext:(CGContextRef)context gradientStartPoint:(CGPoint)gradientStartPoint gradientEndPoint:(CGPoint)gradientEndPoint{
	//繪製漸變色
	UIColor *tintColor = self.tintColor;
	UIColor *tintColor2 = self.tintColor2;
	if(tintColor||tintColor2){
		CGFloat R0 = 0, G0 = 0, B0 = 0, A0 = 1;
		CGFloat R1 = 0, G1 = 0, B1 = 0, A1 = 1;
		
		if(tintColor){
			[tintColor getRed:&R0 green:&G0 blue:&B0 alpha:&A0];
		}
		if(tintColor2){
			[tintColor2 getRed:&R1 green:&G1 blue:&B1 alpha:&A1];
		}
		
		const CGFloat locations[] = {0,1};
		const CGFloat components[] = {
			R0,G0,B0,A0,
			R1,G1,B1,A1
		};
		CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
		CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, sizeof(locations)/sizeof(locations[0]));
		
		CGContextDrawLinearGradient(context, gradient, gradientStartPoint, gradientEndPoint, 0);
		
		CGColorSpaceRelease(colorSpace);
		CGGradientRelease(gradient);
	}
}
- (void)setContentView:(UIView *)v {
	if (v != _contentView) {
		_contentView = v;
		_contentView.frame = self.contentRect;
		[self addSubview:_contentView];
	}
}
- (CGSize)contentSize {
	return self.contentRect.size;
}
/**
 *	計算內容視圖的實際顯示區域
 */
- (CGRect)contentRect {
	UIEdgeInsets contentMargin = self.contentMargin;
	CGRect rect = CGRectMake(_roundedRectangleRect.origin.x+contentMargin.left,
							 _roundedRectangleRect.origin.y+contentMargin.top,
							 _roundedRectangleRect.size.width-contentMargin.left-contentMargin.right,
							 _roundedRectangleRect.size.height-contentMargin.top-contentMargin.bottom);
	return rect;
}

- (void)layoutSubviews{
	self.contentView.frame = self.contentRect;
}
- (CGPoint)arrowPoint{
	CGPoint point = CGPointZero;
	switch (_arrowDirection) {
		case UIPopoverArrowDirectionDown:	//v
			point = CGPointMake(CGRectGetMidX(_arrowRect), CGRectGetMaxY(_arrowRect));
			break;
		case UIPopoverArrowDirectionUp:		//^
			point = CGPointMake(CGRectGetMidX(_arrowRect), CGRectGetMinY(_arrowRect));
			break;
		case UIPopoverArrowDirectionLeft:	//<
			point = CGPointMake(CGRectGetMinX(_arrowRect), CGRectGetMidY(_arrowRect));
			break;
		case UIPopoverArrowDirectionRight:	//>
			point = CGPointMake(CGRectGetMaxX(_arrowRect), CGRectGetMidY(_arrowRect));
			break;
		default:
			break;
	}
	return point;
}

- (void)setContentSize:(CGSize)contentSize withAnimated:(BOOL)animated{
	CGRect contentViewBounds = self.contentView.bounds;
	if(CGSizeEqualToSize(contentSize, contentViewBounds.size)){	//尺寸沒有變化
		return;
	}
	contentViewBounds.size = contentSize;
	if(animated){
		CGRect oldContentViewBounds = self.contentView.bounds;
		//計算出動畫後的frame
		self.contentView.bounds = contentViewBounds;
		[self refresh];
		CGRect newContentViewBounds = self.contentView.bounds;
		
		//還原回去
		self.contentView.bounds = oldContentViewBounds;
		[self refresh];
		
		if(!_animated){
			_animated = YES;
			if(_animateDuration==0) _animateDuration = 0.2;	//總時間是0.2秒
			_startContentSize = self.contentView.bounds.size;
			_endContentSize = newContentViewBounds.size;
			_startTime = [[NSDate date] timeIntervalSince1970];
			_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawView:)];
			[_displayLink setFrameInterval:1];
			[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
		}
	}else{
		self.contentView.bounds = contentViewBounds;
		[self refresh];
	}
	
}
/**
 *	使用自定義動畫時,進行繪圖操作
 */
- (void)drawView:(CADisplayLink *)displayLink{
	NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
	NSTimeInterval duration = timestamp-_startTime;
	NSTimeInterval total = _animateDuration;
	CGFloat perent = duration/total;
	CGRect bounds = self.contentView.bounds;
	bounds.size = perent>=1?_endContentSize:CGSizeMake(_startContentSize.width+(_endContentSize.width-_startContentSize.width)*perent, _startContentSize.height+(_endContentSize.height-_startContentSize.height)*perent);
	self.contentView.bounds = bounds;
	[self refresh];
	if(perent>1){
		[self stopAnimate];
	}
}
/**
 *	停止動畫
 */
- (void)stopAnimate{
	[_displayLink invalidate];
	_animated = NO;
}
- (void)dealloc{
//	NSLog(@"dealloc:%@",self);
}
@end
